//递归方式
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function (root) {
    const result = [];
    const traversal = (root) => {
        if (!root) return;
        result.push(root.val)
        if (root.left) traversal(root.left);
        if (root.right) traversal(root.right);
    }

    traversal(root);
    return result;
};


// 非递归方式
// 用的是栈而不是队列
var preorderTraversal = function (root) {
    if (root == null) return [];
    const stack = [],
        res = [];
    stack.push(root);
    while (stack.length) {
        const node = stack.pop();
        res.push(node.val);
        // 左孩子后进先出，进行先左后右的深度优先遍历
        if (node.right) stack.push(node.right);
        if (node.left) stack.push(node.left);
    }
    return res;
};